<?php

namespace app\utils;

use \Firebase\JWT\{JWT as SJwt,SignatureInvalidException,ExpiredException,BeforeValidException};

class Jwt {

    //签名秘钥
    private $private_key = 'MengBiao_392817654$.php';

    //签名方式
    private $sign_type = 'HS256';

    //payload部分
    private $payload = [
        'iss' => 'mengbiao', //签发者
        'iat' => 0,  //签发时间
//        'exp' => 0,  //过期时间
        'nbf' => 0,  //在什么时间之后该jwt才可用
    ];

    /**
     * jwt初始化
     * @param $option array 其他参数
     */
    private function initPayload(array $option = []) : void {
        $nowtime  = request()->time();
        $this->payload['iat'] = $nowtime ;
//        $this->payload['exp'] = $nowtime + $days * 86400 ; //有效期1天
        $this->payload['nbf'] = $nowtime; //生成之后马上生效
        if (!empty($option)) {
            $this->payload = array_merge($option, $this->payload);
        }
    }

    /**
     * @param $data array 需要加密的额外数据
     * @return string jwt加密字符串
     */
    public function buildToken(array $data = []) : string {
        $this->initPayload($data);
        return SJwt::encode($this->payload, $this->private_key, $this->sign_type);
    }

    /**
     * 解析jwt
     * @param $token string jwt密文
     * @return array
     */
    public function parseToken(string $token) : array {
        try {
            $payload = SJwt::decode($token, $this->private_key,[$this->sign_type]);
            return success('解析成功', (array)$payload);
        } catch (SignatureInvalidException | ExpiredException | BeforeValidException | \UnexpectedValueException | \Exception $e) {
            $err_msg = '登录信息非法：'. $e->getMessage();
            return error($err_msg);
        }
    }
}
